package vtt.android.cartoon_video.adapters;

import java.text.ParseException;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

import necvn.android.youtube_helper.entities.YoutubeItemResult;
import vtt.android.cartoon_video.R;
import vtt.android.cartoon_video.entities.YoutubeItem;
import vtt.android.library.VttBaseApplication;
import vtt.android.library.utils.VttGA;
import vtt.android.library.utils.VttLog;
import vtt.android.library.utils.VttUtils;
import android.content.Context;
import android.graphics.Bitmap;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import butterknife.ButterKnife;
import butterknife.InjectView;

import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;

public class BaseListAdapter extends ArrayAdapter<YoutubeItemResult> {

    protected VttLog log = new VttLog("BaseListAdapter", VttBaseApplication.isDebuggable);
	protected Context mContext;
	protected List<YoutubeItemResult> items;
	
	protected ImageLoader imageLoader = ImageLoader.getInstance();
	protected ImageLoadingListener animateFirstListener = new AnimateFirstDisplayListener();
	protected DisplayImageOptions options;
	
	public BaseListAdapter(Context context, List<YoutubeItemResult> items) {
		super(context, 0, items);
		this.mContext = context;
		this.items = items;
		
		options = getDisplayImageOptions();
		
		// reset before add item into it
		AnimateFirstDisplayListener.displayedImages.clear();
	}

    @Override
	public View getView(int position, View view, ViewGroup parent) {
        ViewHolder holder;
        if (view == null) {
            LayoutInflater layoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            view = layoutInflater.inflate(R.layout.row_youtube_item, null);
            holder = new ViewHolder(view);
            view.setTag(holder);
        }
        holder = (ViewHolder) view.getTag();
        final YoutubeItemResult resultItem = items.get(position);

        String imgUrl = resultItem.snippet.thumbnails.defaultUrl;
        imageLoader.displayImage(imgUrl, holder.image, options, animateFirstListener);
        holder.title.setText(resultItem.snippet.title);
        String date = resultItem.snippet.publishedAt;

        try {
            date = VttUtils.formatDate(date, "yyyy-MM-dd'T'HH:mm:ss", "yyyy-MM-dd HH:mm");
        } catch (ParseException e) {
            e.printStackTrace();
        }

        String des = "Date: " + date;
        if (des != null) {
            holder.description.setVisibility(View.VISIBLE);
            holder.description.setText(des);
        } else {
            holder.description.setVisibility(View.GONE);
        }

        return view;
    }

    static class ViewHolder {
//        @InjectView(R.id.admob_view)
//        AdView adView;
        @InjectView(R.id.row_content)
        View rowContent;
        @InjectView(R.id.img_thumbnail)
        ImageView image;
        @InjectView(R.id.tv_title)
        TextView title;
        @InjectView(R.id.tv_author_date)
        TextView description;

        public ViewHolder(View view) {
            ButterKnife.inject(this, view);
        }
    }

	private static class AnimateFirstDisplayListener extends SimpleImageLoadingListener {

		static final List<String> displayedImages = Collections.synchronizedList(new LinkedList<String>());

		@Override
		public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
			if (loadedImage != null) {
				ImageView imageView = (ImageView) view;
				boolean firstDisplay = !displayedImages.contains(imageUri);
				if (firstDisplay) {
					FadeInBitmapDisplayer.animate(imageView, 500);
					displayedImages.add(imageUri);
				}
			}
		}
	}
	
	/**
	 * getDisplayImageOptions
	 * @return
	 */
	public DisplayImageOptions getDisplayImageOptions(){
	    return new DisplayImageOptions.Builder()
        .showImageOnLoading(R.drawable.ic_no_image)
        .showImageForEmptyUri(R.drawable.ic_no_image)
        .showImageOnFail(R.drawable.ic_no_image)
        .cacheInMemory(true)
        .cacheOnDisk(true)
        .bitmapConfig(Bitmap.Config.RGB_565)
        .imageScaleType(ImageScaleType.IN_SAMPLE_POWER_OF_2)
        .build();
	}
	
    /**
     * show admob
     * @param adView
     */
    public void showAdmob(AdView adView){
        AdRequest adRequest = new AdRequest.Builder()
//              .addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
//              .addTestDevice("48E2C2D828FA6A1F4F39381EF243EBAA")
                .build();
        
        adView.setAdListener(new AdListener() {
            @Override
            public void onAdOpened() {
                VttGA.sendEvent(mContext, "Admob Clicked", "Clicked admob in listview", null, 0);
            }
        });
        
        adView.loadAd(adRequest);
        
    }
}
